package com.studentstreet;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.studentstreet.component.AbstractCommonActivity;
import com.studentstreet.component.LoadStateView;
import com.studentstreet.component.LwtAlertDialog;
import com.studentstreet.entities.UserEntity;
import com.studentstreet.tools.HttpHelper;
import com.studentstreet.tools.PreferenceTools;
import com.studentstreet.tools.SyncImageLoader;
import com.studentstreet.tools.Util;
import com.studentstreet.tools.dbhelper.UserDBHelper;

/**
 * @author likebamboo
 * 
 */
public class PersonalActivity extends AbstractCommonActivity {
	// LoadView
	private LoadStateView loadView = null;
	// 头像图片ImageView
	private ImageView userHeadIv = null;
	// 用户名TextView
	private TextView userNameTv = null;
	// 电话
	private TextView userTelTv = null;
	// 住址
	private TextView userAddrTv = null;
	// 性别
	private TextView userSexTv = null;
	// 邮箱
	private TextView userEmailTv = null;
	// 街龄
	private TextView userAgeTv = null;
	// 小区
	private TextView userCampusTv = null;
	// 籍贯
	private TextView userNativeTv = null;

	// 订单统计
	private TextView userOrderCountTv = null;
	// 订单跟踪
	private TextView userOrderTrackTv = null;

	// 用户名
	private String userName = "";
	// 用户数据Json
	private String userJson = "";
	// 用户实体
	private UserEntity user = null;

	// 标记用户数据未取到
	private static final int USER_IS_EMPTY = 0x10001;
	// 标记用户数据已取到
	private static final int USER_INFO = 0x10002;

	// 用于将数据保存到数据库
	private UserDBHelper dbHelper = null;

	private Button logoutBt = null;

	private SyncImageLoader imageLoader = new SyncImageLoader();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal);
		// 将当前Activity压入堆栈中
		MyApp.getInstance().addActivity(this);
		dbHelper = new UserDBHelper(this);
		// 初始化布局
		loadView = (LoadStateView) findViewById(R.id.downloadStatusBox);
		userHeadIv = (ImageView) findViewById(R.id.user_head);
		userNameTv = (TextView) findViewById(R.id.user_name);
		userTelTv = (TextView) findViewById(R.id.user_tel);
		userEmailTv = (TextView) findViewById(R.id.user_email);
		userAddrTv = (TextView) findViewById(R.id.user_addr);
		userSexTv = (TextView) findViewById(R.id.user_sex);
		userAgeTv = (TextView) findViewById(R.id.user_age);
		userCampusTv = (TextView) findViewById(R.id.user_campus);
		userNativeTv = (TextView) findViewById(R.id.user_nativePlace);

		userOrderCountTv = (TextView) findViewById(R.id.user_order_count);
		userOrderTrackTv = (TextView) findViewById(R.id.user_order_track);

		userOrderCountTv.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(PersonalActivity.this,
						OrderCountActivity.class);
				startActivity(intent);
			}
		});
		userOrderTrackTv.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(PersonalActivity.this,
						OrderTrackActivity.class);
				startActivity(intent);
			}
		});

		// OEM++ liwt@2012-02-21 注销按钮
		if (Util.OEM) {
			logoutBt = (Button) findViewById(R.id.user_logout);
			logoutBt.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					LwtAlertDialog.Builder builder = new LwtAlertDialog.Builder(
							PersonalActivity.this);
					builder.setTitle(R.string.user_logout)
							.setMessage(
									getString(R.string.logout_message, userName))
							.setPositiveButton(R.string.sure,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											logout();
											dialog.dismiss();
										}
									})
							.setNegativeButton(R.string.cancel,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.dismiss();
										}
									});
					Dialog dialog = builder.create();
					dialog.show();
				}
			});
		}
	}

	/**
	 * 退出登录
	 */
	private void logout() {
		PreferenceTools prefTools = new PreferenceTools(getApplicationContext());
		if (prefTools.cleanUserInfo()) {
			Toast.makeText(getApplicationContext(),
					getResources().getString(R.string.logout_success),
					Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(PersonalActivity.this,
					MainActivity.class);
			startActivity(intent);
		} else {
			Toast.makeText(getApplicationContext(),
					getResources().getString(R.string.logout_failed),
					Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		Resources res = getResources();
		PreferenceTools prefTools = new PreferenceTools(this);
		// 判断是否已经登录
		if (!prefTools.isLogin()) {
			// 如果未登录，显示提示对话框
			LwtAlertDialog.Builder builder = new LwtAlertDialog.Builder(this);
			builder.setTitle(res.getString(R.string.login))
					.setIcon(res.getDrawable(android.R.drawable.ic_dialog_info))
					.setMessage(res.getString(R.string.user_no_login))
					.setPositiveButton(res.getString(R.string.sure),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent intent = new Intent(
											PersonalActivity.this,
											LoginDialog.class);
									startActivity(intent);
									// finish();
								}
							})
					.setNegativeButton(res.getString(R.string.cancel),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent intent = new Intent(
											PersonalActivity.this,
											MainActivity.class);
									startActivity(intent);
									finish();
								}
							})
					// 屏蔽返回按键
					.setOnKeyListener(new DialogInterface.OnKeyListener() {
						@Override
						public boolean onKey(DialogInterface dialog,
								int keyCode, KeyEvent event) {
							if (keyCode == KeyEvent.KEYCODE_BACK) {
								return true;
							}
							return false;
						}
					}).show();
			return;
		}
		userName = prefTools.getUserName();
		if ("".equals(userName)) {
			// 当用户名为空时显示空信息
			sendMessage(USER_IS_EMPTY);
		}
		// 查询当前数据库是否有该用户的数据,如果有，则从本地加载数据
		user = dbHelper.getUser(userName);
		if (!"".equals(user.getName())) {
			initUserInfo();
		} else {
			// 当本地数据库没有东西时
			// 启动加载送货信息线程，加载送货信息
			Thread userMsg = new Thread(new UserMsgThread());
			userMsg.start();
		}
	}

	// 加载用户信息线程
	class UserMsgThread implements Runnable {
		@Override
		public void run() {
			// 使用apache HTTP客户端实现
			String urlStr = Util.BASE_URL + "/servlet/UserServlet";
			// 创建网络连接工具对象
			HttpHelper helper = new HttpHelper(urlStr);
			// 添加参数
			// 用户名
			helper.addParam("user_name", userName);
			// 获得服务器返回的数据
			userJson = helper.getResponse();
			// 获得的用户数据为空
			if ("".equals(userJson)) {
				sendMessage(USER_IS_EMPTY);
				return;
			}
			// 将用户Json数据转化为实体对象
			Gson gson = new Gson();
			user = gson.fromJson(userJson, UserEntity.class);
			// 将数据保存到数据库中
			dbHelper.saveToDB(userJson);
			// 发送一个Message通知用户数据更新
			sendMessage(USER_INFO);
		}
	}

	@Override
	protected void handleOtherMessage(int flag) {
		super.handleOtherMessage(flag);
		switch (flag) {
		case USER_INFO:
			loadView.stopLoad();
			// 填充用户信息
			initUserInfo();
			break;
		case USER_IS_EMPTY:
			loadView.showError();
			break;
		default:
			break;
		}
	}

	// 填充用户信息
	private void initUserInfo() {
		userNameTv.setText(user.getName());
		userAddrTv.setText(user.getAddr());
		userTelTv.setText(user.getTel());
		userEmailTv.setText(user.getEmail());
		userSexTv.setText(user.getSex());
		// OEM++ likebamboo@2013-02-21
		userAgeTv.setText(getResources().getString(R.string.user_registe_age,
				calculateTime(user.getRegTime()), user.getRegTime()));
		userNativeTv.setText(user.getOrigin());
		userCampusTv.setText(user.getCampus());

		System.out.println(user.getHeadImgUrl() + "----head");

		if (Util.OEM) {
			imageLoader.loadImage(user.getId(), Util.BASE_SELLERS_LOGO_URL
					+ "/" + user.getHeadImgUrl(),
					new SyncImageLoader.OnImageLoadListener() {
						@Override
						public void onImageLoad(Integer t, Drawable drawable) {
							userHeadIv.setImageDrawable(drawable);
						}

						@Override
						public void onError(Integer t) {
						}
					});
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			MyApp.getInstance().exit(this);
		}
		return super.onKeyDown(keyCode, event);
	}

	// OEM++ liwt@2013-02-21
	// 计算街领
	private String calculateTime(String regTime) {
		String time = "";
		Date d1 = new Date(System.currentTimeMillis());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date d2 = new Date(System.currentTimeMillis());
		try {
			d2 = sdf.parse(regTime);
		} catch (ParseException e) {
			return "";
		}
		long ago = (d1.getTime() - d2.getTime()) / 1000L;// 将时间转化为秒
		long mouth = ago / (3600 * 24 * 30L);// 将时间转化为月
		System.out
				.println(mouth + "------d1+++++ " + d1 + "+++++++++d2++" + d2);
		if (mouth >= 12) {// 大于一年
			mouth = mouth / 12L;
			time = mouth + "年 ";
		} else if (mouth > 0) {// 小于一年，大于1个月
			time = mouth + "个月 ";
		} else {
			time = "不到一个月 ";
		}
		return time;
	}
}
